#!/bin/bash

# 确保以 root 权限运行
if [ "$EUID" -ne 0 ]; then
  echo "Please run as root"
  exit
fi

# 编译所有程序
make clean
make

# 实验参数
FILE_SIZE_MB=512
STRIDE_KB=1024 # 1MB stride, a classic case where default readahead fails
BLOCK_KB=4

# 寻找块设备，请根据你的系统修改
DEVICE=$(lsblk -o NAME,TYPE,MOUNTPOINT | grep "part /" | awk '{print $1}')
DEVICE="/dev/$(basename $DEVICE)"
echo "Using block device: $DEVICE"

# 清理系统缓存的函数
clear_caches() {
    echo "Clearing page cache, dentries and inodes..."
    sync
    echo 3 > /proc/sys/vm/drop_caches
    sleep 1
}

# 实验函数
run_test() {
    local scenario_name=$1
    local benchmark_cmd=$2

    echo "============================================================"
    echo "Running Scenario: $scenario_name"
    echo "Benchmark command: $benchmark_cmd"
    echo "============================================================"
    
    clear_caches
    
    # 使用 perf stat 收集指标
    # time -p 用于获取 real, user, sys 时间
    # -e page-faults,cache-misses,cache-references 对应你的微观指标
    perf stat -d -d -d -e page-faults,cache-misses,cache-references \
        time -p $benchmark_cmd
    
    echo "------------------------------------------------------------"
    sleep 2
}

# --- 场景A: 无优化基线 (Baseline) ---
echo "## SCENARIO A: BASELINE ##"
blockdev --setra 0 $DEVICE
run_test "Baseline (readahead=0)" "./benchmark $FILE_SIZE_MB stride $STRIDE_KB"


# --- 场景B: 内核默认优化 (Kernel Default) ---
echo -e "\n\n## SCENARIO B: KERNEL DEFAULT ##"
# 恢复默认值 (通常是 256 * 512B = 128KB)
blockdev --setra 256 $DEVICE
run_test "Kernel Default" "./benchmark $FILE_SIZE_MB stride $STRIDE_KB"


# --- 场景C: eBPF 自适应优化 (Our System) ---
echo -e "\n\n## SCENARIO C: OUR SYSTEM ##"
# 禁用内核readahead，避免干扰
blockdev --setra 0 $DEVICE
# 在后台启动我们的预取器
./prefetcher &
PREFETCHER_PID=$!
sleep 2 # 等待 eBPF 程序加载

run_test "eBPF Prefetcher" "./benchmark $FILE_SIZE_MB stride $STRIDE_KB"

# 停止预取器
kill -SIGINT $PREFETCHER_PID
wait $PREFETCHER_PID
echo "eBPF Prefetcher stopped."

# 恢复默认readahead值
blockdev --setra 256 $DEVICE
echo "Experiment finished. Readahead restored to default."